package leetcode_tag.树;

import com.sun.tools.corba.se.idl.toJavaPortable.Helper;
import leetcode.TreeNode;

import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.List;
import java.util.Queue;

public class LeetCode199 {


    public static void main(String[] args) {
        LeetCode199 leetCode199 = new LeetCode199();
        leetCode199.rightSideView(new TreeNode(1));
    }

    List<Integer> res = new ArrayList<>();

    public List<Integer> rightSideView(TreeNode root) {
        dfs(root, 0);
        return res;
    }

    private void dfs(TreeNode node, int depth) {
        if (node == null)
            return;
        if (res.size() == depth)
            res.add(node.val);
        dfs(node.right, depth + 1);
        dfs(node.left, depth + 1);
    }

    public List<Integer> rightSideView1(TreeNode root) {
        List<Integer> result = new ArrayList<>();
        if (root == null)
            return result;
        Queue<TreeNode> queue = new ArrayDeque<>();
        TreeNode emptyNode = new TreeNode(-1);
        queue.add(root);
        queue.add(emptyNode);
        while (!queue.isEmpty()) {
            TreeNode poll;
            int lastNum = -1;
            while ((poll = queue.poll()) != emptyNode) {
                lastNum = poll.val;
                if (poll.left != null)
                    queue.add(poll.left);
                if (poll.right != null)
                    queue.add(poll.right);
            }
            if (lastNum != -1) {
                queue.add(emptyNode);
                result.add(lastNum);
            }
        }
        return result;
    }
}
